package com.rizzo.infrastructure.redis.serializer;

import com.rizzo.infrastructure.redis.key.RedisKey;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.UnsupportedEncodingException;

/**
 * {@link org.springframework.data.redis.serializer.RedisSerializer} that is to be used as a
 * key-serializer for Object-Oriented-Redis keys.
 */
public class RedisKeySerializer implements RedisSerializer<RedisKey> {

    private String charset = "UTF-8";

    @Override
    public byte[] serialize(RedisKey redisKey) throws SerializationException {
        return redisKey.serialize().getBytes();
    }

    @Override
    public RedisKey deserialize(byte[] bytes) throws SerializationException {
        final String keyString;
        try {
            keyString = new String(bytes, charset);
        } catch (UnsupportedEncodingException e) {
            throw new SerializationException("Cannot decode the given bytes!", e);
        }
        return RedisKey.deSerialize(keyString);
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
}
